package cn.yunyichina.provider.pay.wechat.service.impl;

import cn.yunyichina.provider.framework.dubbo.service.AlipayService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.MsgLogExt;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.pay.wechat.sdk.WechatConstant;
import cn.yunyichina.provider.pay.wechat.sdk.WechatSDK;
import cn.yunyichina.provider.pay.wechat.service.WechatMessageService;
import cn.yunyichina.provider.pay.wechat.utils.http.HttpClient;
import cn.yunyichina.provider.pay.wechat.utils.http.HttpConstants;
import cn.yunyichina.provider.pay.wechat.utils.http.HttpResponse;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * Created by Lullaby on 2016/9/21.
 */
@Service
public class WechatMessageServiceImpl implements WechatMessageService {
    private static Logger logger = LoggerFactory.getLogger(WechatMessageServiceImpl.class);
    
    /**
	 * 微信小程序消息发送请求URL
	 */
	private static final String ACCESS_TOKEN_REQUEST_SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=";
    
    /**
	 * 获取医院和平台的消息配置关系
	 * @param hospitalCode
	 * @return
	 */
//	private static HospitalPlatformRelate getMessagePlatform(String hospitalCode) {
//		JSONObject param = new JSONObject();
//		param.put("hospital_code", hospitalCode);
//		param.put("platform_code", "wechat");
//		HospitalPlatformRelate  hospitalPlatformRelate = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.hospital.message.platform.get", JsonUtils.toJsonString(param)).getResult(),HospitalPlatformRelate.class);
//		logger.debug("yyt.base.hospital.message.platform.get返回："+JsonUtils.toJsonString(hospitalPlatformRelate));
//		return hospitalPlatformRelate;
//	}
	
	/**
	 * 微信消息入口
	 * @param strJson hospital_code,to_user,template_id,url,msg_content
	 * @return
	 */
    public ResponseObject sendWechatMessageTemplate(String strJson){
		logger.info("sendWechatMessageTemplate 入参："+strJson);
    	ResponseObject responseObject = sendWechatMessageTemplateReal(strJson);
    	
//    	JSONObject param = JsonUtils.parseObject(strJson);
//    	
//    	/**
//    	 * 平台发送消息
//    	 */
//    	HospitalPlatformRelate hospitalPlatformRelate = getMessagePlatform(param.getString("hospital_code"));
//		if (hospitalPlatformRelate != null && hospitalPlatformRelate.getMsgSendFlag() == 1) {
//			param.put("hospital_code",hospitalPlatformRelate.getPlatformHospitalCode());
//			sendWechatMessageTemplateReal(JsonUtils.toJsonString(param));
//		}
		return responseObject;
    }
    /***
     * 微信模板消息发送 wwb
     * 接口名称：yyt.wechatpay.wechat.message.template.send
     * @param data 参数如 {
    "app_id":"wx8eec93c4779ca801",
    "app_secret":"ebfd48431fd7eecf4b4f6fcc2718a898",
    "to_user":"o4Pp9s7r64xNbRJfUfkOFH5CD0D0",
    "template_id":"mTcvjkZM42kR74_LBIAAw2aKQSvkH2QfMha1pK1BRMg",
    "url":"http://app.yunyichina.cn/mobileApp/register/infos/showOrderInfo?orderNo=Y12016092214091016566&openId",
    "msg_content":{
    "预约医生":"黄琳",
    "预约医院":"江门妇幼保健院",
    "预约科室":"妇科门诊"
        }
    }
     * @return
     */
    public ResponseObject sendWechatMessageTemplateReal(String data){
        ResponseObject responseObject = new ResponseObject();
        
        JSONObject param = JsonUtils.parseObject(data);
        MsgLogExt msgLog = new MsgLogExt();
        String toUser = null;
        
        boolean sendSuccessFlag = false;
        try {
        	PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(param.getJSONObject("payment_setting"), PaymentSettingResponse.class);
        	
        	String appSecret = paymentSettingResponse.getSecretKey();
			String appId = paymentSettingResponse.getPayAppId();
			
			
        	
//			HospitalCodeAndAppVo vo = getHospitalInfo(map.getString("hospital_code"));
//			
//			String appId = vo.getAppId();
//			String appSecret = vo.getPrivateKey();
//        	logger.debug("sendWechatMessageTemplateReal:"+data);
//        	ResCommon<PaymentSettingResponse> responsePayment= PayService.getPayClient().queryPaymentSettingByAppcodeAndOrgcodeAndPaymode(map.getString("org_app_code"), map.getString("hospital_code"), (short)1);
//			if ( ! "0".equals(responsePayment.getResultCode())) {
//				logger.error("小程序发送，无法获得APPID信息");
//				throw new CallException(ErrorCodeDefine.MESSAGE_COMMON,"无法获得APPID信息");
//			}
//			logger.debug("sendWechatMessageTemplateReal获取的app信息："+JsonUtils.toJsonString(responsePayment));
        	
//			PaymentSettingResponse paymentSettingResponse = responsePayment.getResult();
//        	String appSecret = paymentSettingResponse.getSecretKey();
//			String hospitalId = paymentSettingResponse.getOrgId();
//			String appId = paymentSettingResponse.getPayAppId();
			
			toUser =param.getString("to_user");
			String templateId = param.getString("template_id");
			String url = param.getString("url");
			
//        String topcolor = (String) map.get("topcolor");

			msgLog = new MsgLogExt(toUser,appId,appId,"wechat",templateId);
			
			String tocken = WechatSDK.getAccessToken(appId, appSecret);
			String postURL = WechatConstant.SEND_TEMPLATE_MSG + tocken;

			JSONObject reqStr = new JSONObject();
			reqStr.put("touser", toUser);
			reqStr.put("template_id", templateId);
			reqStr.put("url", url);
//        reqStr.put("topcolor", topcolor);
			
			//转成对象，不能以字符串格式赋值，否则发不出去
			reqStr.put("data", JSONObject.parseObject(param.getString("msg_content")));
			
			msgLog.setPushContent(JsonUtils.toJsonString(reqStr));
			
			HttpResponse response = new HttpClient().post(postURL, reqStr.toJSONString(), HttpConstants.JSON_TYPE, HttpConstants.CHARACTER_ENCODING_UTF8);
			logger.info("微信发送返回对象："+JsonUtils.toJsonString(response)+",touser="+toUser);
			if (response.getStatusCode() == 200) {
			    //add by chenjun 20160706 access_token验证不通过，则重新拿取并发送推送请求
			    logger.info("PushMsgUtil-消息推送");
			    int code = response.asJSONObject().getInteger("errcode")==null?0:response.asJSONObject().getInteger("errcode");
			    logger.info("PushMsgUtil-消息推送   response_code=" + code);
			    
			    JSONObject jsonResponse = JsonUtils.parseObject(response.getResponseAsString());
			    if (jsonResponse != null && jsonResponse.getInteger("errcode") == 0) {
			    	
			    	msgLog.setPushStatusSuccess();
			    	responseObject.setResultCodeAndMessage("0", "成功");
			    	logger.debug("微信模板消息发送成功:"+reqStr+",touser="+toUser);
			    	sendSuccessFlag = true;
			    }
			    else {
			    	msgLog.setPushStatusFail();
			    	msgLog.setErrorMsg(JsonUtils.toJsonString(response));
			    	responseObject.setResultCodeAndMessage("9000", "失败");
			    	logger.info("微信模板消息发送失败:"+reqStr+",touser="+toUser);
			    }
			    
			    if (code == 40001) {
			    	WechatSDK.deleteAccessToken(appId);
			        tocken = WechatSDK.getAccessToken(appId, appSecret);
			        logger.info("PushMsgUtil-消息推送,重新获取access_token   access_token_code=" + tocken+",touser="+toUser);
			        postURL = WechatConstant.SEND_TEMPLATE_MSG + tocken;
			        response = new HttpClient().post(postURL, reqStr.toJSONString(), HttpConstants.JSON_TYPE, HttpConstants.CHARACTER_ENCODING_UTF8);
			        if (response.getStatusCode() == 200) {
			            JSONObject responseJson =  response.asJSONObject();
			            if (responseJson != null) {
			                if (0 == responseJson.getInteger("errcode")) {
			                    // 成功
			                    responseObject.setResultCodeAndMessage("0", "成功");
			                    msgLog.setPushStatusSuccess();
			                    sendSuccessFlag = true;
			                } else {
			                    // 失败
			                    responseObject.setResultCodeAndMessage("1", "发送失败");//fixme:错误码的定义
			                    msgLog.setPushStatusFail();
			                    msgLog.setErrorMsg(responseJson.toJSONString());
			                }
			            }
			            
			        }else{
			            responseObject.setResultCodeAndMessage("1", "发送失败");//fixme:错误码的定义
			            msgLog.setPushStatusFail();
	                    msgLog.setErrorMsg(JsonUtils.toJsonString(response));
			        }
			    }
			    
			} else {
				logger.info("微信模板消息发送失败:"+reqStr+",touser="+toUser);
			    responseObject.setResultCodeAndMessage("9000", "发送失败");//fixme:错误码的定义
			    msgLog.setPushStatusFail();
                msgLog.setErrorMsg(JsonUtils.toJsonString(response));
               
                
			}
		} catch (Exception e) {
			logger.error("发送微信模板消息异常："+ErrorCodeDefine.getStackTrace(e)+",touser="+toUser);
			msgLog.setPushStatusException();
            msgLog.setErrorMsg(e.toString());
		}
        finally {
    		String smsMsgContent = JsonUtils.toJsonString(param.get("sms_msg_content"));
        	if ( ! sendSuccessFlag) {
				sendSms(smsMsgContent);
			}
        	
        	//保存发送日志
        	AlipayService.callHumpFromInternal("yyt.alipay.alipaymessage.msg.log.save", JsonUtils.toJsonString(msgLog));
        }
        return responseObject;
    }
    private void sendSms(String smsMsgContent) {
		if (StringUtils.isNotBlank(smsMsgContent)) {
			try {
				JSONObject param = JsonUtils.parseObject(smsMsgContent);
				String mobile = param.getString("sms_mobile");
				if (StringUtils.isNotBlank(mobile)) {
					MessageService.sendSms(smsMsgContent);
				}
				
			}
			catch (Exception ex) {
				logger.error("发送短信错误:"+smsMsgContent,ex);
			}
		}
	}
    /**
	 * 发送文本/客服消息
	 * */
	public static String SEND_KF_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
	
	/**
	 * 发送文本/客服消息
	 * @param strJson org_app_code,org_code,to_user,msg_content
	 * @return
	 */
	public static ResponseObject sendWechatMessageText(String strJson) {
		logger.debug("sendWechatMessageText:"+strJson);
		JSONObject jsonObj = JsonUtils.parseObject(strJson);
		
		PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(jsonObj.getJSONObject("payment_setting"), PaymentSettingResponse.class);
    	
    	String appSecret = paymentSettingResponse.getSecretKey();
		String appId = paymentSettingResponse.getPayAppId();
		
//		ResCommon<PaymentSettingResponse> responsePayment= PayService.getPayClient().queryPaymentSettingByAppcodeAndOrgcodeAndPaymode(jsonObj.getString("org_app_code"), jsonObj.getString("org_code"), jsonObj.getShortValue("platform_type"));
//		if ( ! "0".equals(responsePayment.getResultCode())) {
//			logger.error("无法获得APPID信息");
//			throw new CallException(ErrorCodeDefine.MESSAGE_COMMON,"无法获得APPID信息");
//		}
//		logger.debug("获取的app信息："+JsonUtils.toJsonString(responsePayment));
//		PaymentSettingResponse paymentSettingResponse = responsePayment.getResult();
//    	String appSecret = paymentSettingResponse.getSecretKey();
//		String hospitalId = paymentSettingResponse.getOrgId();
//		String appId = paymentSettingResponse.getPayAppId();
		
		
		return sendWechatMessageTextReal(jsonObj.getString("to_user"),appId,appSecret,jsonObj.getString("msg_content"));
	}
    /**
	 * 发送客服消息 sendWechatMessageTexts
	 * @param to_user
	 * @param appId
	 * @param appSecret
	 * @param msgContent
	 * @return
	 */
	public static ResponseObject sendWechatMessageTextReal(String toUser, String appId, String appSecret,
			String msgContent) {
		MsgLogExt msgLog = new MsgLogExt();
		ResponseObject responseObject = new ResponseObject();
		try {
			logger.debug("sendWechatMessageTextReal:"+toUser);
			msgLog = new MsgLogExt(toUser, appId, appId, "wechat", "no template");

			String postURL = SEND_KF_MESSAGE + WechatSDK.getAccessToken(appId, appSecret);

			JSONObject reqStr = new JSONObject();
			JSONObject text = new JSONObject();
			// 反转义特殊字符,比如换行符和回车符,如果取到的内容包含明文的换行符或者回车符,防止java不自动转义,比如 \n或者\r
			text.put("content", StringEscapeUtils.unescapeJava(msgContent));
			reqStr.put("touser", toUser);
			reqStr.put("msgtype", "text");
			reqStr.put("text", text);
			logger.info(reqStr.toString());
			msgLog.setPushContent(JsonUtils.toJsonString(reqStr));
			
			HttpResponse response = new HttpClient().post(postURL, reqStr.toString(), HttpConstants.JSON_TYPE,
					HttpConstants.CHARACTER_ENCODING_UTF8);

			if (response.getStatusCode() == 200) {
				JSONObject jsonResponse = response.asJSONObject();
				if (jsonResponse != null && jsonResponse.getInteger("errcode") == 0) {

					msgLog.setPushStatusSuccess();
					responseObject.setResultCodeAndMessage("0", "成功");
					logger.debug("微信文本消息发送成功:" + reqStr+",touser="+toUser);
				} else {
					msgLog.setPushStatusFail();
					msgLog.setErrorMsg(JsonUtils.toJsonString(response));
					responseObject.setResultCodeAndMessage("9000", "发送失败");
					logger.debug("微信文本消息发送失败:" + reqStr+",touser="+toUser);
				}
			} else {
				responseObject.setResultCodeAndMessage("9000", "调用微信失败");
			}
		} catch (Exception e) {
			logger.error("发送微信文本消息异常："+ErrorCodeDefine.getStackTrace(e)+",touser="+toUser);
			msgLog.setPushStatusException();
			msgLog.setErrorMsg(e.toString());
		} finally {
			// 保存发送日志
			AlipayService.callHumpFromInternal("yyt.alipay.alipaymessage.msg.log.save", JsonUtils.toJsonString(msgLog));
		}
		return responseObject;
	}

    /***
     * 申请微信模板id wwb
     * 接口名称：yyt.wechatpay.wechat.push.template.id.get
     * @param data
     * @return
     */
    public ResponseObject getWechatPushTemplateId(String data){
        ResponseObject responseObject = new ResponseObject();

        Map<String,Object> map = JsonUtils.parseObject(data,Map.class);
        String appId = (String) map.get("app_id");
        String templateShortId = (String) map.get("template_short_Id");
        String appSecret = (String) map.get("app_secret");

        String tocken = WechatSDK.getAccessToken(appId, appSecret);
        String postURL = WechatConstant.GET_TEMPLATE_ID + tocken;
        JSONObject reqStr = new JSONObject();
        reqStr.put("template_id_short", templateShortId);
        HttpResponse response = new HttpClient().post(postURL, reqStr.toJSONString(), HttpConstants.JSON_TYPE, HttpConstants.CHARACTER_ENCODING_UTF8);
        if (response.getStatusCode() == 200) {
            logger.info("PushMsgUtil-根据模版短ID获取模版ID");
            int code = response.asJSONObject().getInteger("errcode")==null?0:response.asJSONObject().getInteger("errcode");
            logger.info("PushMsgUtil-根据模版短ID获取模版ID  response_code=" + code);
            if (code == 40001) {
                tocken = WechatSDK.getAccessTokenByWechat(appId, appSecret);
                logger.info("PushMsgUtil-消息推送,重新获取access_token   access_token_code=" + tocken);
                postURL = WechatConstant.SEND_TEMPLATE_MSG + tocken;
                response = new HttpClient().post(postURL, reqStr.toJSONString(), HttpConstants.JSON_TYPE, HttpConstants.CHARACTER_ENCODING_UTF8);
                if (response.getStatusCode() == 200) {
                    JSONObject jsonObject =  response.asJSONObject();
                    if (jsonObject != null && jsonObject.getInteger("errcode") == 0) {
                        responseObject.setResultObject(jsonObject);
                        responseObject.setResultCodeAndMessage("0","成功");
                    } else {
                        responseObject.setResultCodeAndMessage("-1","失败");// FIXME: 2016/9/22 错误码
                    }
                }else{
                    responseObject.setResultCodeAndMessage("-1","失败");// FIXME: 2016/9/22 错误码
                }
            }
        } else {
            responseObject.setResultCodeAndMessage("-1","失败");// FIXME: 2016/9/22 错误码
        }
        return responseObject;
    }
	
	/***
     * 小程序模板消息发送<br>
     * yyt.wechatpay.wechat.message.template.by.access.token.send
		说明：https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#接口说明
     * @param touser 接收者（用户）的 openid
     * @param templateId 所需下发的模板消息的id
     * @param page 点击模板查看详情跳转页面，不填则模板无跳转
     * @param formId 表单或支付ID
     * @param data 参数对象
     * @param emphasisKeyword 模板需要放大的关键词，不填则默认无放大
     * @param orgAppCode
		调用参数
		<pre>
		{
		  "touser": "OPENID",  
		  "template_id": "TEMPLATE_ID", 
		  "page": "index",          
		  "form_id": "FORMID",         
		  "data": {
		      "keyword1": {
		          "value": "339208499", 
		          "color": "#173177"
		      }, 
		      "keyword2": {
		          "value": "2015年01月05日 12:30", 
		          "color": "#173177"
		      }, 
		      "keyword3": {
		          "value": "粤海喜来登酒店", 
		          "color": "#173177"
		      } , 
		      "keyword4": {
		          "value": "广州市天河区天河路208号", 
		          "color": "#173177"
		      } 
		  },
		  "emphasis_keyword": "keyword1.DATA" 
		}
		</pre>
     * @return
     */
    public ResponseObject sendWechatMessageTemplateByAccessToken(String strJson) {
    	logger.debug("sendWechatMessageTemplateByAccessToken:"+strJson);
    	JSONObject param = JsonUtils.parseObject(strJson);
    	
    	String page = param.containsKey("page") ? param.getString("page") : "";
    	String emphasisKeyword = param.containsKey("emphasis_keyword") ? param.getString("emphasis_keyword") : "";
    	String devOrgCode = param.containsKey("org_code") ? param.getString("org_code") : "";
    	if ( ! StringUtils.isBlank(emphasisKeyword)) {
    		if (emphasisKeyword.indexOf(".") < 0) {
    			emphasisKeyword = emphasisKeyword+".DATA";
    		}
    	}
    	PaymentSettingResponse paymentSettingResponse = JsonUtils.parseObject(param.getJSONObject("payment_setting"), PaymentSettingResponse.class);
    	
    	String appSecret = paymentSettingResponse.getSecretKey();
		String appId = paymentSettingResponse.getPayAppId();
		
    	return sendWechatMessageTemplateByAccessTokenReal(param.getString("to_user"),param.getString("template_id"),page,param.getString("form_id"),JsonUtils.parseObject(param.get("msg_content")),emphasisKeyword,param.getString("org_app_code"),devOrgCode,appId,appSecret);
    	
    }
    
    /***
     * 小程序模板消息发送
		说明：https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#接口说明
     * @param to_user 接收者（用户）的 openid
     * @param templateId 所需下发的模板消息的id
     * @param page 点击模板查看详情跳转页面，不填则模板无跳转
     * @param formId 表单或支付ID
     * @param data 参数对象
     * @param emphasisKeyword 模板需要放大的关键词，不填则默认无放大
     * @param org_app_code
		调用参数
		<pre>
		{
		  "touser": "OPENID",  
		  "template_id": "TEMPLATE_ID", 
		  "page": "index",          
		  "form_id": "FORMID",         
		  "data": {
		      "keyword1": {
		          "value": "339208499", 
		          "color": "#173177"
		      }, 
		      "keyword2": {
		          "value": "2015年01月05日 12:30", 
		          "color": "#173177"
		      }, 
		      "keyword3": {
		          "value": "粤海喜来登酒店", 
		          "color": "#173177"
		      } , 
		      "keyword4": {
		          "value": "广州市天河区天河路208号", 
		          "color": "#173177"
		      } 
		  },
		  "emphasis_keyword": "keyword1.DATA" 
		}
		</pre>
     * @return
     */

    public ResponseObject sendWechatMessageTemplateByAccessTokenReal(String toUser,String templateId,String page,String formId,Map data,String emphasisKeyword,String orgAppCode,String devOrgCode,final String appId,final String appSecret) {
        ResponseObject responseObject = new ResponseObject();
        
        MsgLogExt msgLog = new MsgLogExt();
        try {
        	logger.debug("sendWechatMessageTemplateByAccessToken:入口，orgCode="+orgAppCode+"touser="+toUser);
			
//			HospitalCodeAndAppVo vo = getHospitalInfo(orgAppCode);
//			
//			logger.debug("sendWechatMessageTemplateByAccessToken:HospitalCodeAndAppVo"+JsonUtils.toJsonString(vo));
//			
//			String appSecret = vo.getPrivateKey();
//			String hospitalId = vo.getHospitalId();
//			String appId = vo.getAppId();
//			
//        	logger.debug("获取appid信息"+"touser="+toUser);
//        	ResCommon<PaymentSettingResponse> responsePayment= PayService.getPayClient().queryPaymentSettingByAppcodeAndOrgcodeAndPaymode(orgAppCode, devOrgCode, (short)15);
//			if ( ! "0".equals(responsePayment.getResultCode())) {
//				logger.error("小程序发送，无法获得APPID信息");
//				throw new CallException(ErrorCodeDefine.MESSAGE_COMMON,"无法获得APPID信息");
//			}
//			logger.debug("获取的app信息："+JsonUtils.toJsonString(responsePayment)+"touser="+toUser);
//        	
//			PaymentSettingResponse paymentSettingResponse = responsePayment.getResult();
//        	String appSecret = paymentSettingResponse.getSecretKey();
//			String hospitalId = paymentSettingResponse.getOrgId();
//			String appId = paymentSettingResponse.getPayAppId();
			
			msgLog = new MsgLogExt(toUser,appId,appId,"wechat",templateId);
			
			String accessTocken = WechatSDK.getAccessToken(appId, appSecret);
			String postURL = ACCESS_TOKEN_REQUEST_SEND_URL + accessTocken;

			JSONObject jsonRequest = new JSONObject();
			jsonRequest.put("touser", toUser);
			jsonRequest.put("template_id", templateId);
			
			if ( ! StringUtils.isBlank(page)) {
				jsonRequest.put("page", page);
			}
			
			jsonRequest.put("form_id", formId);
			
			if ( ! StringUtils.isBlank(emphasisKeyword)) {
				jsonRequest.put("emphasis_keyword", emphasisKeyword);
			}
			jsonRequest.put("data", data);
			
			
			logger.debug("accessToken:jsonRequest"+JsonUtils.toJsonString(jsonRequest));
			
			msgLog.setPushContent(JsonUtils.toJsonString(jsonRequest));
			
			HttpResponse response = new HttpClient().post(postURL, jsonRequest.toJSONString(), HttpConstants.JSON_TYPE, HttpConstants.CHARACTER_ENCODING_UTF8);
			logger.debug("accessToken微信发送返回对象："+JsonUtils.toJsonString(response)+"touser="+toUser);
			if (response.getStatusCode() == 200) {
			    //add by chenjun 20160706 access_token验证不通过，则重新拿取并发送推送请求
			    logger.info("accessToken-消息推送");
			    int code = response.asJSONObject().getInteger("errcode")==null?0:response.asJSONObject().getInteger("errcode");
			    logger.info("accessToken-消息推送   response_code=" + code+"touser="+toUser);
			    
			    JSONObject jsonResponse = JsonUtils.parseObject(response.getResponseAsString());
			    if (jsonResponse != null && jsonResponse.getInteger("errcode") == 0) {
			    	
			    	msgLog.setPushStatusSuccess();
			    	responseObject.setResultCodeAndMessage("0", "成功");
			    	logger.debug("accessToken微信模板消息发送成功:"+jsonRequest+"touser="+toUser);
			    }
			    else {
			    	msgLog.setPushStatusFail();
			    	msgLog.setErrorMsg(JsonUtils.toJsonString(response));
			    	responseObject.setResultCodeAndMessage("9000", "发送失败："+jsonResponse.toJSONString());
			    	logger.debug("accessToken微信模板消息发送失败:"+jsonRequest+"touser="+toUser);
			    }
			    
			    
			} else {
				logger.debug("accessToken微信模板消息发送失败:"+jsonRequest+"touser="+toUser);
			    responseObject.setResultCodeAndMessage("9000", "发送失败");//fixme:错误码的定义
			    msgLog.setPushStatusFail();
                msgLog.setErrorMsg(JsonUtils.toJsonString(response));
                
			}
		} 
        catch (CallException ce) {
			logger.error(ce.toString());
			throw ce;
            
		}
        catch (Exception e) {
        	logger.error("小程序消息发送异常："+ErrorCodeDefine.getStackTrace(e)+",touser="+toUser);
			msgLog.setPushStatusException();
            msgLog.setErrorMsg(e.toString());
            responseObject.setResultCodeAndMessage(ErrorCodeDefine.MESSAGE_COMMON, "小程序消息异常"+e.toString());
		}
        finally {

        	
        	//保存发送日志
        	AlipayService.callHumpFromInternal("yyt.alipay.alipaymessage.msg.log.save", JsonUtils.toJsonString(msgLog));
        }
        return responseObject;
    }

}
